-- Radical by Basil Voronkov
-- Module 'musplayer'
---------------------------------------------
-- This module contains an implementation of a musplayer
-- that can play music and sound based on location and conditions.
require "lib/core"
require "lib/tact"

musplayer = {}

function musplayer.proto(o)
  return {
     sfx        = o.sfx
    ,file       = o.file
    ,inside     = function(s, loc)
                    s.loc = loc;
                    return s;
                  end
    ,when       = function (s, cnd)
                    s.cnd = cnd;
                    return s;
                  end
    ,loop       = function(s, loop)
                    if loop == nil then
                      s.lp = 0;
                    else
                      s.lp = loop;
                    end
                    return s;
                  end
    ,fade       = function(s, fid, fout)
                    s.fadein = fid;
                    s.fadeout = fout;
                    return s;
                  end
    ,always     = function(s)
                    s.alw = true;
                    return s;
                  end
    ,channel    = function(s, n)
                    s.ch = n;
                    return s;
                  end
  }
end

function sfx(file)
  return musplayer.proto { 
    sfx = true,
    file = file
  };
end

function mus(file)
  return musplayer.proto {
    file = file
  }
end

function mute()
  return musplayer.proto { }
end

function musplayer.select_music(s,hw)
  for i,v in ipairs(s.mus) do
    local nam = '_m'..tostring(i);
      if (not s[nam] or v.alw) and (v.cnd == nil or apply(v.cnd)) and (v.loc == nil or v.loc == hw) then
        if v.sfx then
          play_sound(v.file,v.lp,v.ch);
        else
          play_music(v.file,v.lp,v.fadeout,v.fadein);
        end
        s[nam] = true;
      end
  end
end

function musplayer.player(o)
  return obj {
     nam        = ""
    ,mus        = o
    ,play       = function(s)
                    local hw = deref(here());
                    musplayer.select_music(s,hw);
                  end
    ,activate   = function(s)
                    _activemusplayer = deref(s);
                  end
  }
end

function musplayer.init()
  tact_resident:add(
    "musplayer",
    function()
      if _activemusplayer ~= nil then
        ref(_activemusplayer):play();
      end
    end
  );
  _activemusplayer = nil;
end
